using System;
using System.Collections.Generic;
using System.IO;

namespace Weever.Json.Serialization.v1
{
    public class JsonSerializerFactory: IJsonSerializerFactory
    {
        private Dictionary<Type, IGeneratedJsonSerializer> _generatedSerializers;
        private JsonSerializerBuilder _builder;

        public JsonSerializerFactory()
        {
            this._generatedSerializers = new Dictionary<Type, IGeneratedJsonSerializer>();
            this._builder = new JsonSerializerBuilder();
        }

        public IJsonSerializer CreateSerializer(Type objType)
        {
            IGeneratedJsonSerializer serializer;
            if (_generatedSerializers.TryGetValue(objType, out serializer))
                return (IJsonSerializer) serializer.Clone();
            else {
                Type type = _builder.Build(objType);
                serializer = (IGeneratedJsonSerializer) Activator.CreateInstance(type, this);
                _generatedSerializers.Add(objType, serializer);
                return serializer;
            }
        }


        public IJsonWriter CreateWriter(TextWriter writer)
        {
            return new JsonWriter(writer);
        }
    }
}
